package com.eyolo.grpcclient.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.stub.MetadataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import scwrapper.SCWrapperGrpc;
import scwrapper.Sc;

/**
 * @Description TODO
 * @Author fanhailong
 * @Date 2021/12/14 11:04
 **/
@Component
@Slf4j
public class GrpcClientManager {

    @Value("${scgrpc.serverPort}")
    private Integer serverPort;

    @Value("${scgrpc.host}")
    private String host;

    public boolean applyExchange() {
        ManagedChannel managedChannel = null;
        try {
            managedChannel = ManagedChannelBuilder.forAddress(host, serverPort).usePlaintext().build();
            SCWrapperGrpc.SCWrapperBlockingStub scWrapperBlockingStub = SCWrapperGrpc.newBlockingStub(managedChannel);
            Metadata metadata = new Metadata();
            metadata.put(Metadata.Key.of("userId", Metadata.ASCII_STRING_MARSHALLER), "123211");
            scWrapperBlockingStub = MetadataUtils.attachHeaders(scWrapperBlockingStub, metadata);

            Sc.ApplyExchangeReq exchangeReq = Sc.ApplyExchangeReq.newBuilder()
                    .setFromCoinName("usdx")
                    .setToCoinName("usdx")
                    .setFromAmount("123")
                    .setBusIdentity("applyId")
                    .build();
            scWrapperBlockingStub.applyExchange(exchangeReq);
            log.info("铸销币申请grpc调用成功");
            return true;
        } catch (Exception e) {
            log.error("提交铸销币申请失败", e);
            return false;
        } finally {
            if (managedChannel != null) {
                managedChannel.shutdown();
            }
        }
    }

}
